using OrchardCore.ContentManagement;
using System;

namespace Lombiq.HelpfulLibraries.OrchardCore.Contents;

public static class ContentExceptionHelpers
{
    /// <summary>
    /// 如果给定的 <paramref name="content"/> 的 <c>ContentType</c> 与 <paramref name="expectedType"/> 不匹配，则抛出 <see cref="ArgumentException"/>。
    /// </summary>
    /// <param name="content">要检查其 <c>ContentType</c> 的内容。</param>
    /// <param name="expectedType">预期的内容类型。</param>
    /// <param name="paramName">要在异常中显示的参数名称。</param>
    public static void ThrowIfNotValidContentType(IContent content, string expectedType, string paramName)
    {
        if (content.ContentItem.ContentType != expectedType)
        {
#pragma warning disable S2302 // "nameof" should be used
            throw new ArgumentException($"Parameter {paramName} is not of the {expectedType} content type.", paramName);
#pragma warning restore S2302 // "nameof" should be used
        }
    }

    /// <summary>
    /// 如果给定的 <paramref name="content"/> 没有指定 <typeparamref name="TElement"/> 类型的元素，则抛出 <see cref="ArgumentException"/>。
    /// </summary>
    /// <param name="content">要检查其元素的内容。</param>
    /// <param name="paramName">要在异常中显示的参数名称。</param>
    public static void ThrowIfHasNoElement<TElement>(IContent content, string paramName)
        where TElement : ContentElement
    {
        if (!content.ContentItem.Has<TElement>())
        {
            throw new ArgumentException($"Parameter {paramName} has no {typeof(TElement).Name} attached to it.", paramName);
        }
    }
}
